import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Button, Modal, Input, message, Tag, Avatar, Tooltip, Space, Tabs } from 'antd';
import { PlusOutlined, EyeOutlined, CopyOutlined, EditOutlined, DeleteOutlined, UserOutlined, FormOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import { FormSchema } from './FormDesigner';

interface FormTemplate {
  id: string;
  name: string;
  description: string;
  category: string;
  schema: FormSchema;
  thumbnail?: string;
  author: string;
  authorName: string;
  createdAt: string;
  updatedAt: string;
  usageCount: number;
  tags: string[];
  isPublic: boolean;
}

interface FormTemplatesProps {
  onSelectTemplate?: (template: FormTemplate) => void;
  onCreateFromTemplate?: (template: FormTemplate) => void;
}

const FormTemplates: React.FC<FormTemplatesProps> = ({
  onSelectTemplate,
  onCreateFromTemplate
}) => {
  const [templates, setTemplates] = useState<FormTemplate[]>([]);
  const [loading, setLoading] = useState(false);
  const [previewVisible, setPreviewVisible] = useState(false);
  const [selectedTemplate, setSelectedTemplate] = useState<FormTemplate | null>(null);
  const [searchText, setSearchText] = useState('');
  const [selectedCategory, setSelectedCategory] = useState<string>('all');
  const [activeTab, setActiveTab] = useState('all');

  // 模拟模板数据
  const mockTemplates: FormTemplate[] = [
    {
      id: '1',
      name: '用户注册表单',
      description: '标准的用户注册表单，包含基本信息收集字段',
      category: '用户管理',
      schema: {
        title: '用户注册表单',
        description: '请填写以下信息完成注册',
        layout: 'vertical',
        fields: [
          {
            id: 'field_1',
            type: 'input',
            label: '用户名',
            name: 'username',
            required: true,
            placeholder: '请输入用户名'
          },
          {
            id: 'field_2',
            type: 'input',
            label: '邮箱',
            name: 'email',
            required: true,
            placeholder: '请输入邮箱地址'
          },
          {
            id: 'field_3',
            type: 'input',
            label: '手机号',
            name: 'phone',
            required: true,
            placeholder: '请输入手机号'
          },
          {
            id: 'field_4',
            type: 'select',
            label: '性别',
            name: 'gender',
            required: false,
            placeholder: '请选择性别',
            options: [
              { label: '男', value: 'male' },
              { label: '女', value: 'female' }
            ]
          }
        ]
      },
      author: 'admin',
      authorName: '系统管理员',
      createdAt: '2024-01-15T10:00:00Z',
      updatedAt: '2024-01-20T15:30:00Z',
      usageCount: 245,
      tags: ['注册', '用户', '基础'],
      isPublic: true
    },
    {
      id: '2',
      name: '请假申请表单',
      description: '员工请假申请表单，包含请假类型、时间、原因等信息',
      category: '人事管理',
      schema: {
        title: '请假申请表单',
        description: '请填写请假申请信息',
        layout: 'vertical',
        fields: [
          {
            id: 'field_1',
            type: 'input',
            label: '申请人',
            name: 'applicant',
            required: true,
            placeholder: '请输入申请人姓名'
          },
          {
            id: 'field_2',
            type: 'select',
            label: '请假类型',
            name: 'leaveType',
            required: true,
            placeholder: '请选择请假类型',
            options: [
              { label: '年假', value: 'annual' },
              { label: '病假', value: 'sick' },
              { label: '事假', value: 'personal' },
              { label: '调休', value: 'compensatory' }
            ]
          },
          {
            id: 'field_3',
            type: 'date',
            label: '开始日期',
            name: 'startDate',
            required: true,
            placeholder: '请选择开始日期'
          },
          {
            id: 'field_4',
            type: 'date',
            label: '结束日期',
            name: 'endDate',
            required: true,
            placeholder: '请选择结束日期'
          },
          {
            id: 'field_5',
            type: 'textarea',
            label: '请假原因',
            name: 'reason',
            required: true,
            placeholder: '请详细说明请假原因'
          }
        ]
      },
      author: 'user001',
      authorName: '张三',
      createdAt: '2024-01-10T09:00:00Z',
      updatedAt: '2024-01-18T14:20:00Z',
      usageCount: 189,
      tags: ['请假', '人事', '审批'],
      isPublic: true
    },
    {
      id: '3',
      name: '客户反馈表单',
      description: '收集客户反馈和建议的表单',
      category: '客户服务',
      schema: {
        title: '客户反馈表单',
        description: '您的反馈对我们很重要',
        layout: 'vertical',
        fields: [
          {
            id: 'field_1',
            type: 'input',
            label: '客户姓名',
            name: 'customerName',
            required: true,
            placeholder: '请输入您的姓名'
          },
          {
            id: 'field_2',
            type: 'input',
            label: '联系方式',
            name: 'contact',
            required: true,
            placeholder: '请输入手机号或邮箱'
          },
          {
            id: 'field_3',
            type: 'select',
            label: '反馈类型',
            name: 'feedbackType',
            required: true,
            placeholder: '请选择反馈类型',
            options: [
              { label: '产品建议', value: 'suggestion' },
              { label: '问题反馈', value: 'issue' },
              { label: '服务投诉', value: 'complaint' },
              { label: '其他', value: 'other' }
            ]
          },
          {
            id: 'field_4',
            type: 'rate',
            label: '满意度评分',
            name: 'satisfaction',
            required: false,
            placeholder: '请为我们的服务评分'
          },
          {
            id: 'field_5',
            type: 'textarea',
            label: '详细反馈',
            name: 'feedback',
            required: true,
            placeholder: '请详细描述您的反馈内容'
          }
        ]
      },
      author: 'user002',
      authorName: '李四',
      createdAt: '2024-01-12T11:30:00Z',
      updatedAt: '2024-01-22T16:45:00Z',
      usageCount: 156,
      tags: ['反馈', '客户', '服务'],
      isPublic: true
    },
    {
      id: '4',
      name: '活动报名表单',
      description: '活动报名信息收集表单',
      category: '活动管理',
      schema: {
        title: '活动报名表单',
        description: '请填写报名信息',
        layout: 'vertical',
        fields: [
          {
            id: 'field_1',
            type: 'input',
            label: '姓名',
            name: 'name',
            required: true,
            placeholder: '请输入您的姓名'
          },
          {
            id: 'field_2',
            type: 'input',
            label: '手机号',
            name: 'phone',
            required: true,
            placeholder: '请输入手机号'
          },
          {
            id: 'field_3',
            type: 'input',
            label: '公司/组织',
            name: 'company',
            required: false,
            placeholder: '请输入公司或组织名称'
          },
          {
            id: 'field_4',
            type: 'checkbox',
            label: '参与环节',
            name: 'sessions',
            required: true,
            placeholder: '请选择参与的环节',
            options: [
              { label: '主题演讲', value: 'keynote' },
              { label: '技术分享', value: 'tech_share' },
              { label: '圆桌讨论', value: 'panel' },
              { label: '网络交流', value: 'networking' }
            ]
          },
          {
            id: 'field_5',
            type: 'textarea',
            label: '特殊需求',
            name: 'requirements',
            required: false,
            placeholder: '如有特殊需求请说明'
          }
        ]
      },
      author: 'user003',
      authorName: '王五',
      createdAt: '2024-01-08T14:15:00Z',
      updatedAt: '2024-01-25T10:20:00Z',
      usageCount: 98,
      tags: ['活动', '报名', '收集'],
      isPublic: true
    },
    {
      id: '5',
      name: '产品调研表单',
      description: '产品需求和用户体验调研表单',
      category: '市场调研',
      schema: {
        title: '产品调研表单',
        description: '帮助我们了解您的需求',
        layout: 'vertical',
        fields: [
          {
            id: 'field_1',
            type: 'select',
            label: '年龄段',
            name: 'ageGroup',
            required: true,
            placeholder: '请选择年龄段',
            options: [
              { label: '18-25岁', value: '18-25' },
              { label: '26-35岁', value: '26-35' },
              { label: '36-45岁', value: '36-45' },
              { label: '46岁以上', value: '46+' }
            ]
          },
          {
            id: 'field_2',
            type: 'radio',
            label: '使用频率',
            name: 'frequency',
            required: true,
            placeholder: '请选择使用频率',
            options: [
              { label: '每天', value: 'daily' },
              { label: '每周', value: 'weekly' },
              { label: '每月', value: 'monthly' },
              { label: '偶尔', value: 'rarely' }
            ]
          },
          {
            id: 'field_3',
            type: 'rate',
            label: '产品满意度',
            name: 'satisfaction',
            required: true,
            placeholder: '请为产品评分'
          },
          {
            id: 'field_4',
            type: 'checkbox',
            label: '希望改进的功能',
            name: 'improvements',
            required: false,
            placeholder: '请选择希望改进的功能',
            options: [
              { label: '界面设计', value: 'ui' },
              { label: '功能完善', value: 'features' },
              { label: '性能优化', value: 'performance' },
              { label: '用户体验', value: 'ux' }
            ]
          },
          {
            id: 'field_5',
            type: 'textarea',
            label: '其他建议',
            name: 'suggestions',
            required: false,
            placeholder: '请提供其他建议或意见'
          }
        ]
      },
      author: 'user004',
      authorName: '赵六',
      createdAt: '2024-01-05T16:00:00Z',
      updatedAt: '2024-01-20T09:30:00Z',
      usageCount: 67,
      tags: ['调研', '产品', '用户'],
      isPublic: true
    },
    {
      id: '6',
      name: '简历投递表单',
      description: '求职者简历投递和基本信息收集表单',
      category: '人力资源',
      schema: {
        title: '简历投递表单',
        description: '请填写个人信息并上传简历',
        layout: 'vertical',
        fields: [
          {
            id: 'field_1',
            type: 'input',
            label: '姓名',
            name: 'name',
            required: true,
            placeholder: '请输入您的姓名'
          },
          {
            id: 'field_2',
            type: 'input',
            label: '手机号',
            name: 'phone',
            required: true,
            placeholder: '请输入手机号'
          },
          {
            id: 'field_3',
            type: 'input',
            label: '邮箱',
            name: 'email',
            required: true,
            placeholder: '请输入邮箱地址'
          },
          {
            id: 'field_4',
            type: 'select',
            label: '应聘职位',
            name: 'position',
            required: true,
            placeholder: '请选择应聘职位',
            options: [
              { label: '前端工程师', value: 'frontend' },
              { label: '后端工程师', value: 'backend' },
              { label: '产品经理', value: 'pm' },
              { label: '设计师', value: 'designer' }
            ]
          },
          {
            id: 'field_5',
            type: 'number',
            label: '期望薪资(K)',
            name: 'expectedSalary',
            required: false,
            placeholder: '请输入期望薪资'
          },
          {
            id: 'field_6',
            type: 'upload',
            label: '简历附件',
            name: 'resume',
            required: true,
            placeholder: '请上传简历文件'
          }
        ]
      },
      author: 'user005',
      authorName: '孙七',
      createdAt: '2024-01-03T13:45:00Z',
      updatedAt: '2024-01-19T11:15:00Z',
      usageCount: 134,
      tags: ['招聘', '简历', 'HR'],
      isPublic: true
    }
  ];

  useEffect(() => {
    loadTemplates();
  }, []);

  const loadTemplates = async () => {
    setLoading(true);
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 500));
      setTemplates(mockTemplates);
    } catch (error) {
      message.error('加载模板失败');
    } finally {
      setLoading(false);
    }
  };

  const handlePreview = (template: FormTemplate) => {
    setSelectedTemplate(template);
    setPreviewVisible(true);
  };

  const handleUseTemplate = (template: FormTemplate) => {
    onCreateFromTemplate?.(template);
    message.success(`已使用模板：${template.name}`);
  };

  const handleCopyTemplate = (template: FormTemplate) => {
    // 复制模板逻辑
    message.success(`模板已复制：${template.name}`);
  };

  // 获取分类列表
  const categories = ['all', ...Array.from(new Set(templates.map(t => t.category)))];

  // 过滤模板
  const filteredTemplates = templates.filter(template => {
    const matchesSearch = template.name.toLowerCase().includes(searchText.toLowerCase()) ||
                         template.description.toLowerCase().includes(searchText.toLowerCase()) ||
                         template.tags.some(tag => tag.toLowerCase().includes(searchText.toLowerCase()));
    const matchesCategory = selectedCategory === 'all' || template.category === selectedCategory;
    const matchesTab = activeTab === 'all' || 
                      (activeTab === 'my' && template.author === 'current_user') ||
                      (activeTab === 'public' && template.isPublic);
    return matchesSearch && matchesCategory && matchesTab;
  });

  const getCategoryColor = (category: string) => {
    const colors: Record<string, string> = {
      '用户管理': 'blue',
      '人事管理': 'green',
      '客户服务': 'orange',
      '活动管理': 'purple',
      '市场调研': 'cyan',
      '人力资源': 'red'
    };
    return colors[category] || 'default';
  };

  const renderFormPreview = (schema: FormSchema) => {
    return (
      <div style={{ padding: 16, border: '1px solid #d9d9d9', borderRadius: 4, backgroundColor: '#fafafa' }}>
        <h4>{schema.title}</h4>
        {schema.description && <p style={{ color: '#666', marginBottom: 16 }}>{schema.description}</p>}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {schema.fields.slice(0, 5).map(field => (
            <div key={field.id} style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <span style={{ minWidth: 80, fontWeight: 'bold' }}>
                {field.label}{field.required && <span style={{ color: 'red' }}>*</span>}:
              </span>
              <span style={{ 
                padding: '4px 8px', 
                border: '1px solid #d9d9d9', 
                borderRadius: 4, 
                backgroundColor: '#fff',
                flex: 1,
                color: '#999'
              }}>
                {field.placeholder || `${field.type} 字段`}
              </span>
            </div>
          ))}
          {schema.fields.length > 5 && (
            <div style={{ textAlign: 'center', color: '#999' }}>
              ... 还有 {schema.fields.length - 5} 个字段
            </div>
          )}
        </div>
      </div>
    );
  };

  return (
    <div className="form-templates">
      {/* 标签页和搜索 */}
      <div style={{ marginBottom: 16 }}>
        <Tabs
          activeKey={activeTab}
          onChange={setActiveTab}
          tabBarExtraContent={
            <Space>
              <Input.Search
                placeholder="搜索模板名称、描述或标签"
                value={searchText}
                onChange={(e) => setSearchText(e.target.value)}
                style={{ width: 250 }}
              />
              <select
                value={selectedCategory}
                onChange={(e) => setSelectedCategory(e.target.value)}
                style={{ width: 120, height: 32, border: '1px solid #d9d9d9', borderRadius: 6, padding: '0 8px' }}
              >
                <option value="all">全部分类</option>
                {categories.filter(c => c !== 'all').map(category => (
                  <option key={category} value={category}>{category}</option>
                ))}
              </select>
              <Button type="primary" icon={<PlusOutlined />}>
                创建模板
              </Button>
            </Space>
          }
        >
          <Tabs.TabPane tab="全部模板" key="all" />
          <Tabs.TabPane tab="我的模板" key="my" />
          <Tabs.TabPane tab="公共模板" key="public" />
        </Tabs>
      </div>

      {/* 模板列表 */}
      <Row gutter={[16, 16]}>
        {filteredTemplates.map(template => (
          <Col key={template.id} xs={24} sm={12} lg={8} xl={6}>
            <Card
              hoverable
              size="small"
              cover={
                <div style={{ 
                  height: 140, 
                  background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  color: 'white',
                  fontSize: 14,
                  fontWeight: 'bold',
                  flexDirection: 'column',
                  gap: 8
                }}>
                  <FormOutlined style={{ fontSize: 24 }} />
                  <div>{template.name}</div>
                  <div style={{ fontSize: 12, opacity: 0.8 }}>
                    {template.schema.fields.length} 个字段
                  </div>
                </div>
              }
              actions={[
                <Tooltip title="预览">
                  <EyeOutlined onClick={() => handlePreview(template)} />
                </Tooltip>,
                <Tooltip title="使用模板">
                  <CopyOutlined onClick={() => handleUseTemplate(template)} />
                </Tooltip>,
                <Tooltip title="复制模板">
                  <EditOutlined onClick={() => handleCopyTemplate(template)} />
                </Tooltip>
              ]}
            >
              <Card.Meta
                title={
                  <div>
                    <div style={{ marginBottom: 4 }}>{template.name}</div>
                    <Tag color={getCategoryColor(template.category)}>
                      {template.category}
                    </Tag>
                  </div>
                }
                description={
                  <div>
                    <div style={{ 
                      fontSize: 12, 
                      color: '#666', 
                      marginBottom: 8,
                      height: 32,
                      overflow: 'hidden',
                      display: '-webkit-box',
                      WebkitLineClamp: 2,
                      WebkitBoxOrient: 'vertical'
                    }}>
                      {template.description}
                    </div>
                    
                    <div style={{ marginBottom: 8 }}>
                      {template.tags.slice(0, 3).map(tag => (
                        <Tag key={tag} style={{ fontSize: 10 }}>
                          {tag}
                        </Tag>
                      ))}
                      {template.tags.length > 3 && (
                        <Tag style={{ fontSize: 10 }}>+{template.tags.length - 3}</Tag>
                      )}
                    </div>
                    
                    <div style={{ 
                      display: 'flex', 
                      justifyContent: 'space-between', 
                      alignItems: 'center',
                      fontSize: 11,
                      color: '#999'
                    }}>
                      <div>
                        <Avatar size={16} icon={<UserOutlined />} style={{ marginRight: 4 }} />
                        {template.authorName}
                      </div>
                      <div>使用 {template.usageCount} 次</div>
                    </div>
                  </div>
                }
              />
            </Card>
          </Col>
        ))}
      </Row>

      {/* 预览模态框 */}
      <Modal
        title={`模板预览 - ${selectedTemplate?.name}`}
        open={previewVisible}
        onCancel={() => setPreviewVisible(false)}
        width={800}
        footer={[
          <Button key="cancel" onClick={() => setPreviewVisible(false)}>
            关闭
          </Button>,
          <Button key="use" type="primary" onClick={() => {
            if (selectedTemplate) {
              handleUseTemplate(selectedTemplate);
              setPreviewVisible(false);
            }
          }}>
            使用此模板
          </Button>
        ]}
      >
        {selectedTemplate && (
          <div>
            <div style={{ marginBottom: 16 }}>
              <h4>模板信息</h4>
              <p><strong>分类：</strong>{selectedTemplate.category}</p>
              <p><strong>描述：</strong>{selectedTemplate.description}</p>
              <p><strong>作者：</strong>{selectedTemplate.authorName}</p>
              <p><strong>创建时间：</strong>{dayjs(selectedTemplate.createdAt).format('YYYY-MM-DD HH:mm')}</p>
              <p><strong>使用次数：</strong>{selectedTemplate.usageCount}</p>
              <p><strong>字段数量：</strong>{selectedTemplate.schema.fields.length}</p>
              <div>
                <strong>标签：</strong>
                {selectedTemplate.tags.map(tag => (
                  <Tag key={tag} style={{ marginLeft: 4 }}>{tag}</Tag>
                ))}
              </div>
            </div>
            
            <div style={{ marginBottom: 16 }}>
              <h4>表单预览</h4>
              {renderFormPreview(selectedTemplate.schema)}
            </div>
            
            <div>
              <h4>字段列表</h4>
              <div style={{ maxHeight: 200, overflowY: 'auto' }}>
                {selectedTemplate.schema.fields.map((field, index) => (
                  <div key={field.id} style={{ 
                    padding: '8px 12px', 
                    border: '1px solid #f0f0f0', 
                    borderRadius: 4, 
                    marginBottom: 4,
                    display: 'flex',
                    justifyContent: 'space-between',
                    alignItems: 'center'
                  }}>
                    <div>
                      <strong>{field.label}</strong>
                      {field.required && <span style={{ color: 'red', marginLeft: 4 }}>*</span>}
                      <div style={{ fontSize: 12, color: '#666' }}>
                        {field.type} | {field.name}
                      </div>
                    </div>
                    <Tag>{field.type}</Tag>
                  </div>
                ))}
              </div>
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default FormTemplates;